package com.asion.gankapp.view.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.asion.gankapp.R;
import com.asion.gankapp.applacation.MyApp;
import com.asion.gankapp.utils.ChangeByte;
import com.asion.gankapp.utils.ThemeChangeUtil;
import com.asion.gankapp.view.fragments.BenifitFragment;
import com.asion.gankapp.view.fragments.CollectFragment;
import com.asion.gankapp.view.fragments.DownLoadFragment;
import com.asion.gankapp.view.fragments.HomeFragment;

import org.greenrobot.greendao.query.Query;

import java.io.File;

import gl.com.app.User;
import gl.com.app.UserDao;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;
    private Toolbar mToolbar;
    private FrameLayout mContainer;
    private NavigationView mNavView;
    private DrawerLayout mDrawerLayout;
    private ImageView touxiang;
    private TextView login;
    private View headerView;
    private int lastCheckedId;
    private HomeFragment homeFragment = HomeFragment.newInstance();
    private CollectFragment collectFragment = CollectFragment.newInstance();
    private BenifitFragment benifitFragment = BenifitFragment.newInstance();
    private DownLoadFragment downLoadFragment = DownLoadFragment.newInstance();
    private Bitmap bitmap;
    private String name;
    private int size;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ThemeChangeUtil.changeTheme(this);
        setContentView(R.layout.activity_main);
        initView();
        setSupportActionBar(mToolbar);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, 0, 0);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        mNavView.setNavigationItemSelectedListener(this);
        mNavView.setBackgroundColor(Color.WHITE);
        mNavView.setCheckedItem(R.id.main_home);

        setHeaderClick();

        getSupportFragmentManager().beginTransaction().add(R.id.container, homeFragment).commit();

        setUser();
    }

    private void setUser() {
        size = MyApp.getUserDao().queryBuilder().list().size();
        if(size != 0){
            User user = MyApp.getUserDao().queryBuilder().where(UserDao.Properties.Id.eq(size)).build().list().get(0);
            if(user != null){
                login.setText(user.getName());
                if(user.getImageurl() != null){
                    touxiang.setImageBitmap(ChangeByte.Bytes2Bimap(user.getImageurl()));
                }
            }
        }
    }

    //保存状态
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt("lastChecked", lastCheckedId);
        outState.putString("name",name);
        outState.putParcelable("bitmap",bitmap);
    }

    //获取保存状态并设置
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        int lastChecked = savedInstanceState.getInt("lastChecked");
        String name = savedInstanceState.getString("name");
        Bitmap bitmap = savedInstanceState.getParcelable("bitmap");
        if(bitmap != null){
            this.touxiang.setImageBitmap(bitmap);
        }
        if(name != null){
            login.setText(name);
        }
        mNavView.setCheckedItem(lastChecked);
        switch (lastChecked) {
            case R.id.main_home:
                changeFragment(homeFragment, R.id.main_home);
                break;
            case R.id.main_shoucang:
                changeFragment(collectFragment, R.id.main_shoucang);
                break;
            case R.id.fuli_she:
                changeFragment(benifitFragment, R.id.fuli_she);
                break;
            case R.id.download:
                changeFragment(downLoadFragment, R.id.download);
                break;
        }
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mContainer = (FrameLayout) findViewById(R.id.container);
        mNavView = (NavigationView) findViewById(R.id.nav_view);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        headerView = mNavView.getHeaderView(0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        MenuItem item = menu.findItem(R.id.main_menu_more);
        if (ThemeChangeUtil.isChange) {
            item.setIcon(R.mipmap.water);
        } else {
            item.setIcon(R.mipmap.fire);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_menu_search:
                Intent intent = new Intent(this, SearchActivity.class);
                Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.in, R.anim.out).toBundle();
                ActivityCompat.startActivity(this, intent, bundle);
                break;
            case R.id.main_menu_more:
                if (ThemeChangeUtil.isChange) {
                    ThemeChangeUtil.isChange = false;
                } else {
                    ThemeChangeUtil.isChange = true;
                }
                MainActivity.this.recreate();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setHeaderClick() {
        touxiang = ((ImageView) headerView.findViewById(R.id.cricleImage));
        login = ((TextView) headerView.findViewById(R.id.login_btn));
        touxiang.setOnClickListener(v -> {
            if(!login.getText().equals("请登录")){
                showDailog();
            }else{
                Toast.makeText(this, "请先登录！！", Toast.LENGTH_SHORT).show();
            }
        });
        login.setOnClickListener(v -> {
            if(login.getText().equals("请登录")){
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivityForResult(intent, 100);
            }else{
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("您是否要注销？");
                builder.setNegativeButton("SURE",(dailog,which)->{
                    login.setText("请登录");
                    touxiang.setImageResource(R.mipmap.myspace_head_img_default);
                });
                builder.setPositiveButton("CANCLE",null);
                builder.create().show();
            }
        });
    }

    private void showDailog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(new String[]{"拍照", "相册"}, (dalog, which) -> {
            switch (which) {
                case 0:
                    Intent intent1 = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        tempFile = new File(Environment.getExternalStorageDirectory(),
                                PHOTO_FILE_NAME);
                        // 从文件中创建uri
                        Uri uri = Uri.fromFile(tempFile);
                        intent1.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    }
                    // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                    startActivityForResult(intent1, PHOTO_REQUEST_CAREMA);

                    break;
                case 1:
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    break;
            }
            dalog.dismiss();
        });
        builder.setCancelable(true);
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                name = data.getStringExtra("name");
                login.setText(name);
                byte[] touxiang = MyApp.getUserDao().queryBuilder().where(UserDao.Properties.Name.eq(name)).build().list().get(0).getImageurl();
                if(touxiang != null){
                    bitmap = ChangeByte.Bytes2Bimap(touxiang);
                    this.touxiang.setImageBitmap(bitmap);
                }
                Toast.makeText(this, "恭喜你登录成功", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            // 从相机返回的数据
            if (hasSdcard()) {
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(MainActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }
        }else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {
                bitmap = data.getParcelableExtra("data");
                this.touxiang.setImageBitmap(bitmap);
                Query<User> query = MyApp.getUserDao().queryBuilder().where(UserDao.Properties.Id.eq(size)).build();
                User user = query.list().get(0);
                if(bitmap != null){
                    user.setImageurl(ChangeByte.Bitmap2Bytes(bitmap));
                }
                MyApp.getUserDao().update(user);
            }
            try {
                // 将临时文件删除
                tempFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_home:
                changeFragment(homeFragment, R.id.main_home);
                break;
            case R.id.main_shoucang:
                changeFragment(collectFragment, R.id.main_shoucang);
                break;
            case R.id.fuli_she:
                changeFragment(benifitFragment, R.id.fuli_she);
                break;
            case R.id.download:
                changeFragment(downLoadFragment, R.id.download);
                break;
            case R.id.main_details:
                Snackbar.make(mDrawerLayout, "Details", Snackbar.LENGTH_SHORT).show();
                break;
            case R.id.main_exit:
                leaveMe();
                break;
        }
        mDrawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    private void leaveMe() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.cry);
        builder.setTitle("你要离开我了吗？");
        builder.setNegativeButton("SURE", (a, b) -> {
            finish();
            System.exit(0);
        });
        builder.setPositiveButton("CANCLE", null);
        builder.create().show();
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onBackPressed() {
        leaveMe();
    }

    private void changeFragment(Fragment fragment, @IdRes int id) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.container, fragment).commit();
        lastCheckedId = id;
    }

    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }
}
